package io.bhex.app.market.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.market.adapter.MarketListMultiAdapter;
import io.bhex.app.market.bean.FavoriteRecordBean;
import io.bhex.app.market.event.ItemClickStatusListener;
import io.bhex.app.market.presenter.OptionalMarketPresenter;
import io.bhex.app.trade.sort.CoinPairComparator;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FavoriteListResponse;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2020-04-20
 * 邮   箱：
 * 描   述：自选行情列表
 * ================================================
 */

public class OptionalMarketFragment extends BaseFragment<OptionalMarketPresenter, OptionalMarketPresenter.OptionalMarketUI> implements OptionalMarketPresenter.OptionalMarketUI, View.OnClickListener, ItemClickStatusListener, SwipeRefreshLayout.OnRefreshListener {
    public static final int TYPE_BB = 0;//币币
    public static final int TYPE_OPTION = 1;// 期权
    public static final int TYPE_FUTURES = 2;// 合约
    public static final int TYPE_LEVER = 3;// 杠杆
    public static final int TYPE_CONTRACT = 4;// 合约
    private static final String TGA = "MarketListFragment";
    private static final int TOUCH_DOWN_NOTIFY = 1; //触摸down
    private static final int TOUCH_UP_OR_CANCEL_NOTIFY = 2; //触摸up 或者cancel
    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private MarketListMultiAdapter adapter;
    private View emptyView;
    private String tabName = "";
    private View headerView;
    private List<CoinPairBean> mData;
    private View sortVolView;
    private View sortPriceView;
    private View sortChangeView;
    private Map<Integer, SortBtn> sortViews = new HashMap<>();
    //默认无排序 正常排序0-5
    private int sortType = -1;
    private View sortLayoutView;
    //上次时间
    private long lastTime=0l;
    private View btnAddFavorite;
    private TextView sortVolTv;
    private TextView sortPriceTv;
    private TextView sortChangeTv;
    private boolean isTouching =false;
    private boolean isVisible;
    private MarketFragment.HomeMarktControl mHomeControl;

    @Override
    protected OptionalMarketPresenter.OptionalMarketUI getUI() {
        return this;
    }

    @Override
    protected OptionalMarketPresenter createPresenter() {
        return new OptionalMarketPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_optional_market_list_layout,null,false);
    }

    @Override
    protected void initViews() {
        super.initViews();
        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        recyclerView = viewFinder.find(R.id.recyclerView);
        btnAddFavorite = viewFinder.find(R.id.btnAddFavorite);
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        headerView = viewFinder.find(R.id.sortLayoutView);
//        emptyView = layoutInflater.inflate(R.layout.empty_layout, swipeRefresh, false);
//        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
//        layoutParams.height = PixelUtils.dp2px(300);
//        emptyView.setLayoutParams(layoutParams);
//        emptyView.findViewById(R.id.empty_txt).setOnClickListener(this);
//        emptyView.findViewById(R.id.empty_img).setOnClickListener(this);

        mData = new ArrayList<>();
        adapter = new MarketListMultiAdapter(getActivity(),mData, false, "",this);
//        adapter.addHeaderView(headerView);
//            adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        adapter.isFirstOnly(false);
//            adapter.setOnLoadMoreListener(this);
        swipeRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        swipeRefresh.setOnRefreshListener(this);
        swipeRefresh.setEnabled(false);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
//        adapter.setHeaderAndEmpty(true);
//        adapter.setEmptyView(emptyView);

        sortLayoutView = headerView.findViewById(R.id.sortLayoutView);
        sortVolView = headerView.findViewById(R.id.radio_sort_vol);
        sortPriceView = headerView.findViewById(R.id.radio_sort_price);
        sortChangeView = headerView.findViewById(R.id.radio_sort_change);
        SortBtn sortVolBtn = new SortBtn();
        sortVolBtn.setViewId(R.id.radio_sort_vol);
        sortVolBtn.setCheck(false);
        sortVolBtn.setDesc(true);
        sortVolBtn.setBtnIcon((ImageView) headerView.findViewById(R.id.sort_vol_icon));
        sortVolTv = (TextView) headerView.findViewById(R.id.sort_vol);
        sortVolBtn.setBtnTxV(sortVolTv);
        SortBtn sortPriceBtn = new SortBtn();
        sortPriceBtn.setViewId(R.id.radio_sort_price);
        sortPriceBtn.setCheck(false);
        sortPriceBtn.setDesc(true);
        sortPriceBtn.setBtnIcon((ImageView) headerView.findViewById(R.id.sort_price_icon));
        sortPriceTv = (TextView) headerView.findViewById(R.id.sort_price);
        sortPriceBtn.setBtnTxV(sortPriceTv);

        SortBtn sortChangeBtn = new SortBtn();
        sortChangeBtn.setViewId(R.id.radio_sort_change);
        sortChangeBtn.setCheck(false);
        sortChangeBtn.setDesc(true);
        sortChangeBtn.setBtnIcon((ImageView) headerView.findViewById(R.id.sort_change_icon));
        sortChangeTv = (TextView) headerView.findViewById(R.id.sort_change);
        sortChangeBtn.setBtnTxV(sortChangeTv);

        sortViews.put(R.id.radio_sort_vol, sortVolBtn);
        sortViews.put(R.id.radio_sort_price, sortPriceBtn);
        sortViews.put(R.id.radio_sort_change, sortChangeBtn);
        for (Integer key : sortViews.keySet()) {
            SortBtn sortBtn = sortViews.get(key);
            setShadow(sortBtn);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        for (Integer key : sortViews.keySet()) {
            SortBtn sortBtn = sortViews.get(key);
            setShadow(sortBtn);
        }
        sortVolTv.setTextColor(ContextCompat.getColor(getActivity(), CommonUtil.isBlackMode()? R.color.dark_night : R.color.dark));
        sortPriceTv.setTextColor(ContextCompat.getColor(getActivity(), CommonUtil.isBlackMode()? R.color.dark_night : R.color.dark));
        sortChangeTv.setTextColor(ContextCompat.getColor(getActivity(), CommonUtil.isBlackMode()? R.color.dark_night : R.color.dark));
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TOUCH_DOWN_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
                case TOUCH_UP_OR_CANCEL_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
            }
        }
    };


    public void setHomeControl(MarketFragment.HomeMarktControl control){
        mHomeControl = control;
    }

    public boolean isSelected(){
        if(mHomeControl != null){
            return mHomeControl.IsSelected();
        }

        Bundle arguments = getArguments();
        boolean isSelect = true;
        if (arguments != null) {
            isSelect = arguments.getBoolean("isSelect",true);
        }
        return isSelect;
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
        DebugLog.e("MARKET-Update",visible ? "visible   " : "invisible  " + this.hashCode());
        if (visible && isSelected()) {
            getCoinPairListData();
        }
    }



    @Override
    public void onItemStatusListener(boolean isClick) {
        if (isClick) {
            isTouching = true;
            mHandler.sendEmptyMessageDelayed(TOUCH_DOWN_NOTIFY,1000);
        }else{
            mHandler.sendEmptyMessageDelayed(TOUCH_UP_OR_CANCEL_NOTIFY,200);
        }
    }

    /**
     * 获取自选列表
     * @return
     */
    private List<CoinPairBean> getFavorites() {
        //默认都取config接口symbol(全量列表)的实体列表
        HashMap<String, CoinPairBean> bbSymbolMap = SymbolDataManager.GetInstance().getBBSymbolMap();

        /***未登录，添加本地自选**/
        FavoriteRecordBean favoriteRecordBean = KlineUtils.getFavorite();
        List<CoinPairBean> localFavoriteList = favoriteRecordBean.getData();
        if (localFavoriteList == null) {
            localFavoriteList = new ArrayList<>();
        }
        if (bbSymbolMap != null && bbSymbolMap.size()>0) {
            for (CoinPairBean coinPairBean : localFavoriteList) {
                CoinPairBean bbCoin = bbSymbolMap.get(coinPairBean.getSymbolId());
                if (bbCoin != null) {
                    coinPairBean.setTicker(bbCoin.getTicker());
                }

            }
        }
        return localFavoriteList;
    }

    public void getCoinPairListData(){
        if (!isVisible) {
            return;
        }
        if (System.currentTimeMillis()-lastTime<200){
            return;
        }

        Observable.create((ObservableOnSubscribe<List<CoinPairBean>>) emitter -> {

            List<CoinPairBean> coinPairList = getFavorites();

            emitter.onNext(coinPairList);
//                emitter.onComplete();
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<CoinPairBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<CoinPairBean> coinPairList) {
//                        showMarket(coinPairList);
                        if (coinPairList != null && coinPairList.size()>0) {
                            getPresenter().getRealTimeData(coinPairList);
                        }else{
                            showMarket(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });



    }

    @Override
    protected void addEvent() {
        super.addEvent();
        headerView.findViewById(R.id.radio_sort_vol).setOnClickListener(this);
        headerView.findViewById(R.id.radio_sort_price).setOnClickListener(this);
        headerView.findViewById(R.id.radio_sort_change).setOnClickListener(this);
        viewFinder.find(R.id.btnAddFavorite).setOnClickListener(this);

    }

    @Override
    public void onRefresh() {
        setRefreshing(false);
    }


    public void setRefreshing(final boolean refreshing) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refreshing);
            }
        });
    }

    /**
     * 展示行情
     *
     * @param coinPairList
     */
    @Override
    public void showMarket(List<CoinPairBean> coinPairList) {
        if (!isVisible) {
            return;
        }

        if (btnAddFavorite != null) {
            if (coinPairList != null && coinPairList.size()>0) {
                btnAddFavorite.setVisibility(View.GONE);
            }else{
                btnAddFavorite.setVisibility(View.VISIBLE);
            }
        }
        mData = coinPairList;
        if(adapter == null)
            return;
        if (!isTouching) {  //如果处于点击操作时，暂时不更新UI
            if (sortType == -1) {
                adapter.setNewData(mData);
            } else {
                sortByComparator(mData, sortType);
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.empty_txt:
            case R.id.empty_img:
                //TODO 例如重试处理
                break;
            case R.id.radio_sort_vol:
                sort(R.id.radio_sort_vol);
                break;
            case R.id.radio_sort_price:
                sort(R.id.radio_sort_price);
                break;
            case R.id.radio_sort_change:
                sort(R.id.radio_sort_change);
                break;
            case R.id.btnAddFavorite:
                IntentUtils.goSearch(getActivity());
                break;

        }
    }

    /**
     * 排序
     *
     * @param viewId
     */
    private void sort(int viewId) {
        changeSortBtnStatus(viewId);
        if (mData != null) {
            SortBtn sortBtn = sortViews.get(viewId);
            switch (viewId) {
                case R.id.radio_sort_vol:
                    sortType = sortBtn.isDesc() ? CoinPairComparator.SORT_TYPE_VOL_DESC : CoinPairComparator.SORT_TYPE_VOL_ASC;
                    break;
                case R.id.radio_sort_price:
                    sortType = sortBtn.isDesc() ? CoinPairComparator.SORT_TYPE_PRICE_DESC : CoinPairComparator.SORT_TYPE_PRICE_ASC;
                    break;
                case R.id.radio_sort_change:
                    sortType = sortBtn.isDesc() ? CoinPairComparator.SORT_TYPE_CHANGE_DESC : CoinPairComparator.SORT_TYPE_CHANGE_ASC;
                    break;
            }

            sortByComparator(mData, sortType);

        }

    }

    /**
     * 比较器排序
     *
     * @param mData
     * @param sortType
     */
    private void sortByComparator(List<CoinPairBean> mData, int sortType) {
        if (mData != null && mData.size()>0) {
            Collections.sort(mData, new CoinPairComparator(sortType));
        }
        adapter.setNewData(mData);
    }

    /**
     * 修改排序按钮的状态
     *
     * @param viewId
     */
    private void changeSortBtnStatus(int viewId) {
        for (Integer key : sortViews.keySet()) {
            SortBtn sortView = sortViews.get(key);
            if (sortView.getViewId() == viewId && sortView.isCheck()) {
                //如果之前为选中排序状态，再次点击则反向排序
                sortView.setDesc(!sortView.isDesc());
            } else {
                //默认是降序状态
                sortView.setDesc(true);
            }
            if (sortView.getViewId() == viewId) {
                sortView.setCheck(true);
            } else {
                sortView.setCheck(false);
            }
            setShadow(sortView);
            changeBtnTxtAndIcon(sortView);
        }

    }


    /**
     * 设置背景和阴影
     *
     * @param sortBtn
     */
    private void setShadow(SortBtn sortBtn) {
        ShadowDrawable.setShadowDrawable(headerView.findViewById(sortBtn.getViewId()),
                sortBtn.isCheck() ? getResources().getColor(R.color.blue) : getResources().getColor(
                        CommonUtil.isBlackMode() ? R.color.white_night : R.color.white),
                PixelUtils.dp2px(3),
                sortBtn.isCheck() ? getResources().getColor(R.color.blue10) : getResources().getColor(
                        CommonUtil.isBlackMode() ? R.color.dark10_night : R.color.dark10),
                PixelUtils.dp2px(3),
                1,
                PixelUtils.dp2px(1));

    }

    /**
     * 改变排序按钮文本颜色和icon
     *
     * @param sortView
     */
    private void changeBtnTxtAndIcon(SortBtn sortView) {
        if (sortView.isCheck()) {
            sortView.getBtnTxV().setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.white));
            sortView.getBtnIcon().setImageResource(sortView.isDesc() ? R.mipmap.icon_sort_checked_down : R.mipmap.icon_sort_checked_up);
        } else {
            sortView.getBtnTxV().setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
            sortView.getBtnIcon().setImageResource(R.mipmap.icon_sort);
        }
    }

    public class SortBtn {
        private int viewId;
        private TextView btnTxV;
        private ImageView btnIcon;
        private boolean check;//是否选中
        private boolean desc;//是否是降序

        public int getViewId() {
            return viewId;
        }

        public void setViewId(int viewId) {
            this.viewId = viewId;
        }

        public boolean isCheck() {
            return check;
        }

        public void setCheck(boolean check) {
            this.check = check;
        }

        public boolean isDesc() {
            return desc;
        }

        public void setDesc(boolean desc) {
            this.desc = desc;
        }

        public TextView getBtnTxV() {
            return btnTxV;
        }

        public void setBtnTxV(TextView btnTxV) {
            this.btnTxV = btnTxV;
        }

        public ImageView getBtnIcon() {
            return btnIcon;
        }

        public void setBtnIcon(ImageView btnIcon) {
            this.btnIcon = btnIcon;
        }
    }
}
